<?php


namespace Lrental\Tenancy\Generators\Webserver\Vhost;


use Hyn\Tenancy\Contracts\Webserver\ReloadsServices;
use Hyn\Tenancy\Contracts\Webserver\VhostGenerator;
use Hyn\Tenancy\Contracts\Website;
use Hyn\Tenancy\Website\Directory;
use Symfony\Component\Process\Process;

class NginxGenerator implements VhostGenerator, ReloadsServices
{
    /**
     * @var Directory
     */
    private $directory;

    public function __construct(Directory $directory)
    {
        $this->directory = $directory;
    }

    /**
     * @param Website $website
     * @return null|string
     */
    public function media(Website $website)
    {
        return $this->directory->setWebsite($website)->isLocal() && $this->directory->exists('media') ?
            $this->directory->path('media', true) :
            null;
    }

    /**
     * @param Website $website
     * @return string
     */


    public function generate(Website $website): string
    {
        return view('tenancy.generators.webserver.nginx.vhost', [
            'website' => $website,
            'config' => config('webserver.nginx', []),
            'directory' => $this->directory->setWebsite($website),
            'media' => $this->media($website)
        ]);
    }

    /**
     * @param Website $website
     * @return string
     */
    public function targetPath(Website $website): string
    {
        return "{$website->uuid}.conf";
    }

    /**
     * @return bool
     */
    public function reload(): bool
    {
        // TODO need reload
        return true;
        if ($this->testConfiguration() && $reload = config('webserver.nginx.paths.actions.reload')) {
            return (Process::fromShellCommandline($reload))
                ->mustRun()
                ->isSuccessful();
        }

        return false;
    }

    /**
     * @return bool
     */
    public function testConfiguration(): bool
    {
        // TODO need configuration test
        return true;
        $test = config('webserver.nginx.paths.actions.test-config');

        if (is_bool($test)) {
            return $test;
        }

        return (Process::fromShellCommandline($test))
            ->mustRun()
            ->isSuccessful();
    }
}
